package com.cf.r1043_d;

import java.io.*;

public class c1 {

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter out = new PrintWriter(System.out);

    public static void main(String[] args) throws IOException {
        int T = Integer.parseInt(br.readLine());
        while (T-- > 0) {
            solve();
        }
        out.flush();
        out.close();
        br.close();
    }

    static void solve() throws IOException {
        long n = Long.parseLong(br.readLine());
        long ans = 0L;
        for (int bit = 20; bit >= 0; bit--) {
            long p = (long) Math.pow(3, bit);
            if (n >= p) {
                long cnt = n / p;
                long pir = (long) Math.pow(3, bit + 1);
                if (bit >= 1) pir += (long) (bit * Math.pow(3, bit - 1));
                ans += cnt * pir;
                n -= p * cnt;
            }
        }
        out.println(ans);

    }

}
